//
//  Strort_Breakfas_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/25.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//
#import "Strort_Breakfas_Controller.h"
#import "Strort_Breakfast_RightCell.h"

#import "Strort_Breakfast_Bottom.h"

#import "UIImage+ColorToImage.h"
#import "UIColor+Hex.h"
#import "Global.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"

#import "FMDBManager.h"
#import "ManagerHttpBase.h"
#import "XiaoQuAndStoreInfoModel.h"
#import "NSString+Conversion.h"
#import "ManagerGlobeUntil.h"
#import "MTA.h"
@interface Strort_Breakfas_Controller ()<UITableViewDelegate,UITableViewDataSource,Strort_Breakfast_RightCellDelegate>
{
    CGFloat total;
    NSInteger totalSingularInt;
    CGFloat chajia;
    
    CALayer     *layer;
    UIImageView *_imageView;
    CGRect rectx;
    
}
@property (nonatomic ,retain) UITableView*dockTavleView;

@property (nonatomic ,retain) UITableView *rightTableView;


@property (nonatomic ,retain) NSMutableArray *rightArrayFMDB;
@property (nonatomic,strong)NSMutableArray *rightData;
@property (nonatomic ,strong) Strort_Breakfast_Bottom  *btnView;
@property (nonatomic,strong)NSString *shopID;
@property (nonatomic,strong) UIBezierPath *path;

@end

@implementation Strort_Breakfas_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setSubView];
    _rightArrayFMDB=[[NSMutableArray alloc]init];
    _rightData=[[NSMutableArray alloc]init];
    self.title=@"营养早餐";
    [self addBackNavItem];
    [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"暂无数据" inView:self.view];
   
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
  
//    [self initDate];
    //默认选中第一行
    //////这里假设你初始要选中的是第一行
    NSIndexPath *indexPath =[NSIndexPath indexPathForRow:0 inSection:0];
    [self.dockTavleView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
//    [self getTotoaPrice];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:NO];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"营养早餐"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"营养早餐"];
}
-(void)backBtnAction:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark--设置数据源 网络请求
-(void)initDate
{
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    _shopID=[NSString stringISNull:mode.storeID];
    ManagerHttpBase *manager=[ManagerHttpBase sharedManager];
    NSMutableDictionary *parameters =[[NSMutableDictionary alloc]init];
    [manager parameters:parameters customPOST:@"" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dataDic = (NSDictionary*)responseObject;
        NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
        if ([state isEqualToString:@"0"]) {//请求成功
            [self.rightData removeAllObjects];
            [self.rightData addObject:[dataDic objectForKey:@"OBJECT"]];
            [self.rightTableView reloadData];

        }
    } failure:^(bool isFailure) {
        
    }];
}

#pragma mark --rightTableDelegate
- (void)selectedItemAtIndexPath:(NSIndexPath *)indexPath tag:(NSInteger)tag
{
     //tag =11 减  tag=12加
    
    NSMutableDictionary *dic = [self.rightData objectAtIndex:indexPath.row];
    NSMutableDictionary *good =[[FMDBManager sharedManager]QueryDataWithShopID:_shopID goodID:[dic objectForKey:@"ID"]];

    if (good.count==0) {
        
    }else{
        
    }
    //字符串 变数字 然后加减完 变回字符串
    NSString *str=[good objectForKey:@"buynum"];
    NSInteger buynum =str.integerValue;
    if (tag==11) {
        buynum--;
        if (buynum<0) {
            buynum=0;
        }
        if (buynum==0) {
            [[FMDBManager sharedManager]deleteOneDataWithShopID:_shopID goodID:[dic objectForKey:@"ID"]];
        }
    }else{
        buynum++;
        CGRect rectInTableView = [_rightTableView rectForRowAtIndexPath:indexPath];
        
        CGRect rect = [_rightTableView convertRect:rectInTableView toView:[_rightTableView superview]];
        rectx=rect;
        //
        self.path = [UIBezierPath bezierPath];
        [_path moveToPoint:CGPointMake(VIEW_WIDTH-20, rectx.origin.y+50)];
        [_path addLineToPoint:CGPointMake(35,CGRectGetMinY(self.btnView.frame)+10)];
        
        [self startAnimation];
    }
    NSString *srr=[NSString stringWithFormat:@"%ld",(long)buynum];
    [[FMDBManager sharedManager]modifyDataWithshopID:_shopID goodID:[good objectForKey:@"goodID"] buynum:srr];
    //计算价格
    
//    [self getTotoaPrice];
    Strort_Breakfast_RightCell *cell =[[Strort_Breakfast_RightCell alloc]init];
    cell.productQuantity.text=srr;
    //刷新当前cell
    [self.rightTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  
}
#pragma mark--加入数据库
-(void)intoFMDB
{
    
}
#pragma mark--UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag==1)
    {
        return 50;
    }else{
        return 100;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"暂无数据" inView:self.view];
}
#pragma mark--UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag==1) {
        return 5;
    }else{
        return self.rightData.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if (tableView.tag==1) {
        NSArray *array =[[NSArray alloc]initWithObjects:@"中餐套餐", @"凉食套餐",@"主食套餐",@"饮品",@"水果",nil];
        
        NSString *identfy = [NSString stringWithFormat:@"pinpai%ld",(long)indexPath.row];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identfy];
        if (cell == nil) {
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identfy];
            
        }
        cell.backgroundColor=[UIColor colorWithHexString:@"#f2f5f5"];
        cell.textLabel.text = [NSString stringWithFormat:@"%@",[array objectAtIndex:indexPath.row]];
        cell.textLabel.font =[UIFont systemFontOfSize:12.0f];
        cell.textLabel.highlightedTextColor = [UIColor colorWithHexString:@"#ff5555"];
        
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor =[UIColor whiteColor];
        return cell;
        
    }else{
        
        NSString *ID=@"wineID";
        //2.没有则创建cell
        
        Strort_Breakfast_RightCell*cell=[tableView dequeueReusableCellWithIdentifier:ID];
        
        
        if(!cell) {
            cell=[[Strort_Breakfast_RightCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            cell.delegate = self;
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
         cell.indexPath = indexPath;
//         cell.productQuantity.text=
        NSDictionary *dicData=[_rightData objectAtIndex:indexPath.row];
        NSString *goodID=[dicData objectForKey:@"ID"];
        NSDictionary *dic=[[FMDBManager sharedManager]QueryDataWithShopID:_shopID goodID:goodID];
        cell.productQuantity.text=[dic objectForKey:@"BUYNUM"];
        [cell retSubViewWithData:dicData];
        tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
        
        //4.返回cell
        return cell;
        
    }
    
}


#pragma mark--加入物品动画
-(void)startAnimation
{
    if (!layer) {
        
        layer = [CALayer layer];
        layer.contents = (__bridge id)[UIImage imageNamed:@"icon_shopcar_add_1"].CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0,20, 20);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];
}
-(void)groupAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    CABasicAnimation *expandAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    expandAnimation.duration = 0.3f;
    expandAnimation.fromValue = [NSNumber numberWithFloat:1];
    expandAnimation.toValue = [NSNumber numberWithFloat:2.0f];
    expandAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    narrowAnimation.beginTime = 0.3;
    narrowAnimation.fromValue = [NSNumber numberWithFloat:2.0f];
    narrowAnimation.duration = 0.6f;
    narrowAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    
    narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,expandAnimation,narrowAnimation];
    if (rectx.origin.y>200) {
        groups.duration = 0.4f;
    }else if(310>rectx.origin.y){
        groups.duration = 0.6f;
    }else{
        groups.duration=0.8f;
    }
    
    groups.removedOnCompletion=NO;
    groups.fillMode=kCAFillModeForwards;
    groups.delegate = self;
    [layer addAnimation:groups forKey:@"group"];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //    [anim def];
    if (anim == [layer animationForKey:@"group"]) {
        
        [layer removeFromSuperlayer];
        layer = nil;
        //购物车按钮动画
        
        CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        shakeAnimation.duration = 0.3f;
        shakeAnimation.fromValue = [NSNumber numberWithFloat:-1];
        shakeAnimation.toValue = [NSNumber numberWithFloat:1];
        shakeAnimation.autoreverses = YES;
        [_btnView.shopCarBtn.layer addAnimation:shakeAnimation forKey:nil];
    }
    self.path = [UIBezierPath bezierPath];
    [_path moveToPoint:CGPointMake(50, 150)];
    [_path addQuadCurveToPoint:CGPointMake(270, 300) controlPoint:CGPointMake(150, 20)];
    
}
-(void)getTotoaPrice
{
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    _rightArrayFMDB =[[FMDBManager sharedManager]QueryIsChoosedDataWithShopID:[NSString stringISNull:mode.storeID]];
    
    //总金额
    total =0;
    totalSingularInt=0;
    for (NSInteger i=0; i<_rightArrayFMDB.count; i++) {
        NSDictionary *dic =[_rightArrayFMDB objectAtIndex:i];
        total +=[[dic objectForKey:@"SELLPRICE"] floatValue]*[[dic objectForKey:@"BUYNUM"] floatValue];
        totalSingularInt+=[[dic objectForKey:@"BUYNUM"] floatValue];
    }
    _btnView.totalPrice.text=[NSString stringWithFormat:@"总金额:￥%.2f",total];
    //圆标数量
    _btnView.totalSingular.text=[NSString stringWithFormat:@"%ld",(long)totalSingularInt];
    
    if (totalSingularInt!=0) {
        _btnView.totalSingular.hidden=NO;
    }else
    {
        _btnView.totalSingular.hidden=YES;
    }

}

#pragma mark--初始化视图
-(void)setSubView
{
    _dockTavleView =[[UITableView alloc]initWithFrame:(CGRect){0,0,80,VIEW_HEIGHT-64-49}];
    _dockTavleView.rowHeight=60;
    _dockTavleView.delegate=self;
    _dockTavleView.dataSource=self;
    
    _dockTavleView.backgroundColor=[UIColor colorWithHexString:@"#f2f5f5"];
    [_dockTavleView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:_dockTavleView];
    _dockTavleView.tag=1;
    
    
    
    _rightTableView =[[UITableView alloc]initWithFrame:(CGRect){CGRectGetMaxX(_dockTavleView.frame),0,VIEW_WIDTH-CGRectGetWidth(_dockTavleView.bounds),VIEW_HEIGHT-64}];
    _rightTableView.rowHeight=90;
    _rightTableView.delegate=self;
    _rightTableView.dataSource=self;
    [_rightTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _rightTableView.tag=2;
    [self.view addSubview:_rightTableView];
    
    
    _btnView =[[Strort_Breakfast_Bottom alloc]initWithFrame:CGRectMake(10, VIEW_HEIGHT-70-64,CGRectGetWidth(self.view.bounds)/3+30,50)];
    [self.view addSubview:_btnView];
    
}

@end
